package com.app.twth.ui.preprocess;


import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.app.twth.BR;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.app.Constant;
import com.app.twth.base.BaseActivity;
import com.app.twth.databinding.ActivityPreprocessBinding;
import com.app.twth.databinding.DialogLableTrkHintBinding;
import com.app.twth.ui.b2cpick.submit.SKUBarcodes;
import com.app.twth.ui.preprocess.shipment.PreprocessShipmentActivity;
import com.app.twth.utils.EditTextUtil;
import com.app.twth.utils.MyDialogUtil;
import com.app.twth.utils.ToastUtil;
import com.app.twth.utils.Utils;

/**
 * @describe :
 */
public class PreprocessActivity extends BaseActivity<ActivityPreprocessBinding, PreprocessViewModel> {
    private String TAG = getClass().getSimpleName();
    private int type = 0;
    private boolean isTrk;

    @Override
    protected void initListener() {
        viewModel.skuBarcodesLiveData.observe(this, data -> {
            binding.tvQty.requestFocus();
            binding.tvQty.setText(1 + "");
        });

        viewModel.submitLiveData.observe(this, code -> {
            isTrk = true;
            if (code) {
                setSubmit();
            }
        });
        viewModel.errorResultCode.observe(this, code -> {
            showHint((String) code);
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
    }

    protected String setTitle() {
        return "Preprocess(Tracking)";
    }

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        setNext("");
        binding.tvCode.requestFocus();

        binding.tvCode.setOnEditorActionListener(EnterListenter);
        binding.tvCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isTrk = false;
            }
        });
        binding.tvCodeSku.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                viewModel.skuBarcodesLiveData.setValue(null);
            }
        });
        binding.tvCode.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvCodeSku.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvQty.setOnFocusChangeListener(onFocusChangeListener);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        bottomLayoutBinding.tvHint.setText("");
        initScan();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unScan();
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_scan:
                type = 0;
                setScan();
                break;
            case R.id.iv_scan_barcode:
                type = 1;
                setScan();
                break;
            case R.id.tv_reset:
                bottomLayoutBinding.tvHint.setText("");
                binding.tvCode.setText("");
                binding.tvCodeSku.setText("");
                binding.tvQty.setText("1");
                binding.tvCode.requestFocus();
                break;
            case R.id.tv_next:
                if (System.currentTimeMillis() - timeMillis < spaceTime) {//两秒内触发一次
                    return;
                }
                timeMillis = System.currentTimeMillis();
                setSubmit();
                break;
        }
    }

    private TextView.OnEditorActionListener EnterListenter = new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                barcodeStr = binding.tvCode.getText().toString();
                EditTextUtil.hideInput(mContext);
                bottomLayoutBinding.tvHint.setText("");
                if ((!Utils.isEmpty(barcodeStr)) && barcodeStr.length() > 36) {
                    showTrackingDialog();
                } else {
                    viewModel.returnPreprocessCheckTackingCode(barcodeStr, false);
                }
            }
            return false;
        }
    };

    View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                switch (v.getId()) {
                    case R.id.tv_code:
                        type = 0;
                        break;
                    case R.id.tv_code_sku:
                        type = 1;
                        break;
                    case R.id.tv_qty:
                        type = 2;
                        break;
                }
            } else {
                type = 0;
            }
        }
    };

    @Override
    public void getScanninCode() {
        super.getScanninCode();
        switch (type) {
            case 0:
                binding.tvCode.setText(barcodeStr);
                if ((!Utils.isEmpty(barcodeStr)) && barcodeStr.length() > 36) {
                    showTrackingDialog();
                } else {
                    viewModel.returnPreprocessCheckTackingCode(barcodeStr, false);
                }
                break;
            case 1:
                viewModel.getInfoByBarcode(barcodeStr, false);
                binding.tvCodeSku.setText(barcodeStr);
                break;
            case 2:
                try {
                    String barCode = binding.tvCodeSku.getText().toString();
                    if (Utils.isEmpty(barCode)) {
                        mVibrator.vibrate(new long[]{0, 1000}, -1);
                        return;
                    }
                    Log.e(TAG, "barCode:" + barCode);
                    Log.e(TAG, "barcodeStr:" + barcodeStr);
                    SKUBarcodes skuBarcodes = viewModel.skuBarcodesLiveData.getValue();
                    if ((skuBarcodes != null) && (skuBarcodes.getBarcodeList() != null) && (skuBarcodes.getBarcodeList().size() > 0)) {
                        for (String barcode : skuBarcodes.getBarcodeList()) {
                            if (barCode.equalsIgnoreCase(barcode)) {
                                String qty = binding.tvQty.getText().toString();
                                if (Utils.isEmpty(qty)) {
                                    binding.tvQty.setText(1 + "");
                                    return;
                                } else {
                                    binding.tvQty.setText((1 + Integer.parseInt(qty)) + "");
                                    return;
                                }
                            }
                        }
                    } else if (barCode.equalsIgnoreCase(barcodeStr)) {
                        String qty = binding.tvQty.getText().toString();
                        if (Utils.isEmpty(qty)) {
                            binding.tvQty.setText(1 + "");
                        } else {
                            binding.tvQty.setText((1 + Integer.parseInt(qty)) + "");
                        }
                    } else {
                        mVibrator.vibrate(new long[]{0, 1000}, -1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    AlertDialog dialogTracking;

    private void showTrackingDialog() {
        dialogTracking = MyDialogUtil.getDialog(mContext, initTrackingDialogView(), Gravity.CENTER);
        dialogTracking.setCanceledOnTouchOutside(true);
        dialogTracking.show();
    }

    private View initTrackingDialogView() {
        DialogLableTrkHintBinding dialogBinding = DialogLableTrkHintBinding.inflate(getLayoutInflater());
        dialogBinding.tvTrk.setText(R.string.tracking_hint);
        dialogBinding.tvConfirm.setText("Re-scan");
        dialogBinding.tvConfirm.setOnClickListener(v -> {
            binding.tvCode.setText("");
            if (dialogTracking != null) {
                dialogTracking.dismiss();
            }
        });
        dialogBinding.viewLine.setVisibility(View.VISIBLE);
        dialogBinding.tvCancel.setVisibility(View.VISIBLE);
        dialogBinding.tvCancel.setText("Continue");
        dialogBinding.tvCancel.setOnClickListener(v -> {
            if (dialogTracking != null) {
                dialogTracking.dismiss();
            }
            viewModel.returnPreprocessCheckTackingCode(barcodeStr, false);
        });
        return dialogBinding.getRoot();
    }


    private void setSubmit() {
        String tracking = binding.tvCode.getText().toString();
        String code_sku = binding.tvCodeSku.getText().toString();
        if (Utils.isEmpty(tracking)) {
            ToastUtil.showToast("Please input  trk#");
            return;
        }

        if (!isTrk) {
            viewModel.returnPreprocessCheckTackingCode(tracking, true);
            return;
        }
        if (Utils.isEmpty(code_sku)) {
            ToastUtil.showToast("Please input sku/barcode");
            return;
        }
        if (viewModel.skuBarcodesLiveData.getValue() == null) {
            viewModel.getInfoByBarcode(code_sku, true);
            return;
        }
        String qty = binding.tvQty.getText().toString();
        if (Utils.isEmpty(qty)) {
            ToastUtil.showToast("Please input quantity");
            return;
        }

        Log.e(TAG, "(" + qty + ")");
        PreprocessQr bounceReasonQr = new PreprocessQr();
        bounceReasonQr.setTrackingCode(tracking);
        bounceReasonQr.setBarcode(code_sku);
        bounceReasonQr.setQty(Integer.parseInt(qty.trim()));
        Bundle bundle = new Bundle();
        bundle.putSerializable("PreprocessQr", bounceReasonQr);
        AppRouter.showActivityForResult(mContext, PreprocessShipmentActivity.class, bundle, Constant.ForResult2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.ForResult2 && resultCode == RESULT_OK) {
            bottomLayoutBinding.tvHint.setText("");
            binding.tvCode.setText("");
            binding.tvCodeSku.setText("");
            binding.tvQty.setText("1");
            binding.tvCode.requestFocus();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
